/**
 * @date 2022/4/2
 * @description vuex user.js模块
 * @author 
 */

import { login, forceLogin, getMenuList, getUserInfo, logOut } from '@/api/interface/user'

import { sessionstorage } from '@/utils/storage'

import { setting } from '@/config/setting'
const { title, tokenName } = setting
import { resetRouter } from '@/router'
import { deepClone } from '@/utils/common.js'

import store from '@/store'

const state = {
  token: sessionstorage.get('token'),
  menuList: [], //菜单列表
  userInfo: {}, //用户信息
}
const actions = {
  //登录
  async login({ commit }, userInfo) {
    const { status, data } = await login(userInfo)
    if (status === 200) {
      commit('setToken', data)
    } else {
      return status
    }
  },
  //强制登录
  async forceLogin({ commit }, userInfo) {
    const { status, data } = await forceLogin(userInfo)
    if (status === 200) {
      commit('setToken', data)
    }
  },
  //获取菜单
  async getMenuList({ commit, state }) {
    const { data } = await getMenuList()
    // let newData = data[0].childresource.splice(0, 2)
    let newData = data[0].childresource
    if (data.length !== 0) {
      commit('setMenuList', newData)
    }
  },
  //获取当前用户详情
  async getUserInfo({ commit, state }) {
    const { status, data } = await getUserInfo()
    if (status == 200) {
      commit('setUserInfo', data)
    }
  },
  //退出
  async logOut({ dispatch }, token) {
    const param = {
      token: state.token,
      userName: state.userInfo.userName,
      '7moor_token':token||'',
    }
    const { status } = await logOut(param)
    if (status == 200) {
      await dispatch('resetToken')
      await resetRouter()
      const view = store.getters['tabsBar/visitedRoutes']
      await dispatch('tabsBar/delAllRoutes', view, { root: true })
      sessionstorage.clear()
    }

    return status
  },
  resetToken({ commit }) {
    commit('setMenuList', [])
    commit('setToken', null)
  },
}
const mutations = {
  setToken(state, token) {
    state.token = token
    sessionstorage.set('token', token)
    const strings = state.token.split('.') //通过split()方法将token转为字符串数组
    //取strings[1]数组中的第二个字符进行解析
    const userinfo = JSON.parse(
      decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, '+').replace(/_/g, '/'))))
    )
    console.log(userinfo);
    localStorage.setItem('userInfo', JSON.stringify(userinfo));

  },
  setMenuList(state, menuList) {
    state.menuList = deepClone(menuList)
    console.log('state.menuList ',state.menuList );
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
}
const getters = {
  token: (state) => state.token,
  menuList: (state) => state.menuList,
  userInfo: (state) => state.userInfo,
}

export default {
  getters,
  state,
  mutations,
  actions,
}
